#pragma once

#include <stdio.h>
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <iostream>
#include <string>
#include <error.h>

#include "log.hpp"

#define Info 0
#define Warning 1
#define Error 2
#define Fatal 3
#define Debug 4

#define NUM 1024
#define Myfifo "myfifo"
using namespace std;

enum
{
    MYFIFO_CREAT_ERR = 0, // 命名管道创建失败
    CILENT_OPEN_ERR,      // 写入端打开管道失败
    FIFO_CREATE_ERR,
    MYFILE_CREAT_ERR,
    MYFILE_WRITE_ERR
};

class INI
{
public:
    INI()
    {
        int m = mkfifo(Myfifo, 0666);
        if (m < 0)
        {
            // log();  等待实现
            exit(MYFIFO_CREAT_ERR);
        }
        // 会等待对方
        fd = open(Myfifo, O_RDONLY, 0666); // 只读模式打开管道文件
    }

    void Close()
    {
        close(fd);
    }
    ~INI()
    {
        int n = unlink(Myfifo);
        if (n == -1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }

    void work()
    {
        Log log(LocalPath,ClassFile);
        Log log2("./Log/",InputFile);
        log.enable(InputFile);
        char buffer[NUM];
        while (true)
        {
            int r = read(fd, buffer, sizeof(buffer)); // 等待读取
            buffer[r] = 0;
            std::cout << "Receive: " << buffer << std::endl;
            log(Info, "This is %s, error is %d", strerror(errno), errno);
            if (r == 0) // 写端被关闭了
            {
                // log() 输出日志信息：写端关闭
                break;
            }
            log(Warning, "This is %s, error is %d", strerror(errno), errno);
            log(Error, "This is %s, error is %d", strerror(errno), errno);
            log(Fatal, "This is %s, error is %d", strerror(errno), errno);
            log(Debug, "This is %s, error is %d", strerror(errno), errno);
            log2(Info, "This is %s, error is %d", strerror(errno), errno);
            log2.enable(Print);
            log2(Debug, "This is %s, error is %d", strerror(errno), errno);
            buffer[0] = 0;
        }
            log(Debug, "This is %s, error is %d", strerror(errno), errno);
    }

    int fd;
};
